package com.daxue002.header;

import java.util.Iterator;
import java.util.TreeMap;

import com.daxue002.attribute.MessageAttribute;
import com.daxue002.attribute.MessageAttributeParsingException;
import com.daxue002.util.AttributeType;
import com.daxue002.util.MessageType;
import com.daxue002.util.Utility;
import com.daxue002.util.UtilityException;

public class MessageHeader implements MessageHeaderInterface {
	/*
	 * 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | STUN
	 * Message Type | Message Length |
	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	 * 
	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	 * Transaction ID
	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
	 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	 */
	MessageType type;
	byte[] id = new byte[16];

	TreeMap<AttributeType, MessageAttribute> ma = new TreeMap<AttributeType, MessageAttribute>();

	public MessageHeader() {
		super();
	}

	public MessageHeader(MessageType type) {
		super();
		setType(type);
	}

	public void setType(MessageType type) {
		this.type = type;
	}

	public MessageType getType() {
		return type;
	}

	public static int typeToInteger(MessageType type) {
		if (type == MessageType.BindingRequest)
			return BINDINGREQUEST;
		if (type == MessageType.BindingResponse)
			return BINDINGRESPONSE;
		if (type == MessageType.BindingErrorResponse)
			return BINDINGERRORRESPONSE;
		if (type == MessageType.SharedSecretRequest)
			return SHAREDSECRETREQUEST;
		if (type == MessageType.SharedSecretResponse)
			return SHAREDSECRETRESPONSE;
		if (type == MessageType.SharedSecretErrorResponse)
			return SHAREDSECRETERRORRESPONSE;
		return -1;
	}

	public void setTransactionID(byte[] id) {
		System.arraycopy(id, 0, this.id, 0, 16);
	}

	public void generateTransactionID() throws UtilityException {
		System.arraycopy(Utility
				.integerToTwoBytes((int) (Math.random() * 65536)), 0, id, 0, 2);
		System.arraycopy(Utility
				.integerToTwoBytes((int) (Math.random() * 65536)), 0, id, 2, 2);
		System.arraycopy(Utility
				.integerToTwoBytes((int) (Math.random() * 65536)), 0, id, 4, 2);
		System.arraycopy(Utility
				.integerToTwoBytes((int) (Math.random() * 65536)), 0, id, 6, 2);
		System.arraycopy(Utility
				.integerToTwoBytes((int) (Math.random() * 65536)), 0, id, 8, 2);
		System
				.arraycopy(Utility
						.integerToTwoBytes((int) (Math.random() * 65536)), 0,
						id, 10, 2);
		System
				.arraycopy(Utility
						.integerToTwoBytes((int) (Math.random() * 65536)), 0,
						id, 12, 2);
		System
				.arraycopy(Utility
						.integerToTwoBytes((int) (Math.random() * 65536)), 0,
						id, 14, 2);
	}

	public byte[] getTransactionID() {
		byte[] idCopy = new byte[id.length];
		System.arraycopy(id, 0, idCopy, 0, id.length);
		return idCopy;
	}

	public boolean equalTransactionID(MessageHeader header) {
		byte[] idHeader = header.getTransactionID();
		if (idHeader.length != 16)
			return false;
		if ((idHeader[0] == id[0]) && (idHeader[1] == id[1])
				&& (idHeader[2] == id[2]) && (idHeader[3] == id[3])
				&& (idHeader[4] == id[4]) && (idHeader[5] == id[5])
				&& (idHeader[6] == id[6]) && (idHeader[7] == id[7])
				&& (idHeader[8] == id[8]) && (idHeader[9] == id[9])
				&& (idHeader[10] == id[10]) && (idHeader[11] == id[11])
				&& (idHeader[12] == id[12]) && (idHeader[13] == id[13])
				&& (idHeader[14] == id[14]) && (idHeader[15] == id[15])) {
			return true;
		} else {
			return false;
		}
	}

	public void addMessageAttribute(MessageAttribute attri) {
		ma.put(attri.getType(), attri);
	}

	public MessageAttribute getMessageAttribute(
			AttributeType type) {
		return ma.get(type);
	}

	public byte[] getBytes() throws UtilityException {
		int length = 20;
		Iterator<AttributeType> it = ma.keySet()
				.iterator();
		while (it.hasNext()) {
			MessageAttribute attri = ma.get(it.next());
			length += attri.getLength();
		}
		// add attribute size + attributes.getSize();
		byte[] result = new byte[length];
		System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0,
				result, 0, 2);
		System.arraycopy(Utility.integerToTwoBytes(length - 20), 0, result, 2,
				2);
		System.arraycopy(id, 0, result, 4, 16);

		// arraycopy of attributes
		int offset = 20;
		it = ma.keySet().iterator();
		while (it.hasNext()) {
			MessageAttribute attri = ma.get(it.next());
			System.arraycopy(attri.getBytes(), 0, result, offset, attri
					.getLength());
			offset += attri.getLength();
		}
		return result;
	}

	public int getLength() throws UtilityException {
		return getBytes().length;
	}

	public void parseAttributes(byte[] data)
			throws MessageAttributeParsingException {
		try {
			byte[] lengthArray = new byte[2];
			System.arraycopy(data, 2, lengthArray, 0, 2);
			int length = Utility.twoBytesToInteger(lengthArray);
			System.arraycopy(data, 4, id, 0, 16);
			byte[] cuttedData;
			int offset = 20;
			while (length > 0) {
				cuttedData = new byte[length];
				System.arraycopy(data, offset, cuttedData, 0, length);
				MessageAttribute ma = MessageAttribute
						.parseCommonHeader(cuttedData);
				addMessageAttribute(ma);
				length -= ma.getLength();
				offset += ma.getLength();
			}
		} catch (UtilityException ue) {
			throw new MessageAttributeParsingException("Parsing error");
		}
	}

	public static MessageHeader parseHeader(byte[] data)
			throws MessageHeaderParsingException {
		try {
			MessageHeader mh = new MessageHeader();
			byte[] typeArray = new byte[2];
			System.arraycopy(data, 0, typeArray, 0, 2);
			int type = Utility.twoBytesToInteger(typeArray);
			switch (type) {
			case BINDINGREQUEST:
				mh.setType(MessageType.BindingRequest);
				System.out.println("Binding Request received.");
				break;
			case BINDINGRESPONSE:
				mh.setType(MessageType.BindingResponse);
				System.out.println("Binding Response received.");
				break;
			case BINDINGERRORRESPONSE:
				mh.setType(MessageType.BindingErrorResponse);
				System.out.println("Binding Error Response received.");
				break;
			case SHAREDSECRETREQUEST:
				mh.setType(MessageType.SharedSecretRequest);
				System.out.println("Shared Secret Request received.");
				break;
			case SHAREDSECRETRESPONSE:
				mh.setType(MessageType.SharedSecretResponse);
				System.out.println("Shared Secret Response received.");
				break;
			case SHAREDSECRETERRORRESPONSE:
				mh.setType(MessageType.SharedSecretErrorResponse);
				System.out.println("Shared Secret Error Response received.");
				break;
			default:
				throw new MessageHeaderParsingException("Message type " + type
						+ "is not supported");
			}
			return mh;
		} catch (UtilityException ue) {
			throw new MessageHeaderParsingException("Parsing error");
		}
	}
}